<div class="layui-form p-page">
    <div class="doc-card-container">
        <!-- 起诉状 -->
        <div class="doc-card" style="margin-bottom: 20px; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);" data-type-id="1">
            <div class="doc-card-header" style="font-size: 16px; font-weight: bold; padding: 12px 15px; background-color: #f8f8f8; border-left: 4px solid #1E9FFF; margin-bottom: 10px; color: #333;">起诉状<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 15px;" onclick="openUploadDoc(1)">+ 上传文档</button></div>
            <div class="doc-card-body">
                <table class="layui-table" id="docTable" lay-filter="docTable" lay-size="sm"></table>
<script type="text/html" id="docOperateBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="preview">预览</a>
</script>
            </div>
        </div>
        
        <!-- 委托代理材料 -->
        <div class="doc-card" style="margin-bottom: 20px; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);" data-type-id="2">
            <div class="doc-card-header" style="font-size: 16px; font-weight: bold; padding: 12px 15px; background-color: #f8f8f8; border-left: 4px solid #1E9FFF; margin-bottom: 10px; color: #333;">委托代理材料<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 15px;" onclick="openUploadDoc(2)"><i class="layui-icon"></i>上传文档</button></div>
            <div class="doc-card-body">
                <table class="layui-table" id="docTable" lay-filter="docTable" lay-size="sm"></table>
<script type="text/html" id="docOperateBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="preview">预览</a>
</script>
            </div>
        </div>
        
        <!-- 原被告身份证明 -->
        <div class="doc-card" style="margin-bottom: 20px; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);" data-type-id="3">
            <div class="doc-card-header" style="font-size: 16px; font-weight: bold; padding: 12px 15px; background-color: #f8f8f8; border-left: 4px solid #1E9FFF; margin-bottom: 10px; color: #333;">原被告身份证明<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 15px;" onclick="openUploadDoc(2)"><i class="layui-icon"></i>上传文档</button></div>
            <div class="doc-card-body">
                <table class="layui-table" id="docTable" lay-filter="docTable" lay-size="sm"></table>
<script type="text/html" id="docOperateBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="preview">预览</a>
</script>
            </div>
        </div>
        
        <!-- 证据目录及证据材料 -->
        <div class="doc-card" style="margin-bottom: 20px; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);" data-type-id="4">
            <div class="doc-card-header" style="font-size: 16px; font-weight: bold; padding: 12px 15px; background-color: #f8f8f8; border-left: 4px solid #1E9FFF; margin-bottom: 10px; color: #333;">证据目录及证据材料<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 15px;" onclick="openUploadDoc(2)"><i class="layui-icon"></i>上传文档</button></div>
            <div class="doc-card-body">
                <table class="layui-table" id="docTable" lay-filter="docTable" lay-size="sm"></table>
<script type="text/html" id="docOperateBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="preview">预览</a>
</script>
            </div>
        </div>

        <!-- 银行账户确认书 -->
        <div class="doc-card" style="margin-bottom: 20px; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);" data-type-id="5">
            <div class="doc-card-header" style="font-size: 16px; font-weight: bold; padding: 12px 15px; background-color: #f8f8f8; border-left: 4px solid #1E9FFF; margin-bottom: 10px; color: #333;">银行账户确认书<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 15px;" onclick="openUploadDoc(2)"><i class="layui-icon"></i>上传文档</button></div>
            <div class="doc-card-body">
                <table class="layui-table" id="docTable" lay-filter="docTable" lay-size="sm"></table>
<script type="text/html" id="docOperateBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="preview">预览</a>
</script>
            </div>
        </div>

        <!-- 送达地址确认书 -->
        <div class="doc-card" style="margin-bottom: 20px; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);" data-type-id="6">
            <div class="doc-card-header" style="font-size: 16px; font-weight: bold; padding: 12px 15px; background-color: #f8f8f8; border-left: 4px solid #1E9FFF; margin-bottom: 10px; color: #333;">送达地址确认书<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 15px;" onclick="openUploadDoc(2)"><i class="layui-icon"></i>上传文档</button></div>
            <div class="doc-card-body">
                <table class="layui-table" id="docTable" lay-filter="docTable" lay-size="sm"></table>
<script type="text/html" id="docOperateBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="preview">预览</a>
</script>
            </div>
        </div>
        
        <!-- 裁判文书/调解文书 -->
        <div class="doc-card" style="margin-bottom: 20px; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);" data-type-id="7">
            <div class="doc-card-header" style="font-size: 16px; font-weight: bold; padding: 12px 15px; background-color: #f8f8f8; border-left: 4px solid #1E9FFF; margin-bottom: 10px; color: #333;">裁判文书/调解文书<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 15px;" onclick="openUploadDoc(2)"><i class="layui-icon"></i>上传文档</button></div>
            <div class="doc-card-body">
                <table class="layui-table" id="docTable" lay-filter="docTable" lay-size="sm"></table>
<script type="text/html" id="docOperateBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="preview">预览</a>
</script>
            </div>
        </div>
        
        <!-- 其他 -->
        <div class="doc-card" style="margin-bottom: 20px; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 1px 2px rgba(0,0,0,0.1);" data-type-id="8">
            <div class="doc-card-header" style="font-size: 16px; font-weight: bold; padding: 12px 15px; background-color: #f8f8f8; border-left: 4px solid #1E9FFF; margin-bottom: 10px; color: #333;">其他<button type="button" class="layui-btn layui-btn-sm" style="margin-left: 15px;" onclick="openUploadDoc(2)"><i class="layui-icon"></i>上传文档</button></div>
            <div class="doc-card-body">
                <table class="layui-table" id="docTable" lay-filter="docTable" lay-size="sm"></table>
<script type="text/html" id="docOperateBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="preview">预览</a>
</script>
            </div>
        </div>
    </div>
</div>

<script>
function docInit(){

    if($('#caseTab').find('li').eq(3).data('load') == 'true'){
        return false;
    }
    $('#caseTab').find('li').eq(3).data('load','true');

    layui.use(['jquery', 'table', 'layer', 'tool', 'form'], function(){
        var $ = layui.jquery,
            table = layui.table,
            layer = layui.layer,
            tool = layui.tool,
            form = layui.form;

        // 表格操作事件
        table.on('tool(docTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'del'){
                layer.confirm('确认删除该文档？', function(index){
                    tool.post('/lawcase/casedoc/delete', {
                        id: data.id,
                        case_id: $('#case_id').val()
                    }, function(res) {
                        layer.msg(res.msg);
                        if(res.code === 0) {
                            table.reload('docTable');
                        }
                        layer.close(index);
                    });
                });
            } else if(obj.event === 'preview') {
                previewDoc(data.id);
            }
        });

        window.previewDoc = function(id) {
            $.ajax({
                url: '/lawcase/api/get_casedoc_info',
                data: {id: id},
                success: function(res) {
                    if(res.code === 0) {
                        var ext = res.data.fileext;
                        var href = res.data.filepath;
                        var filename = res.data.filename || '';
                        
                        // 根据文件扩展名判断类型
                        var fileExt = filename.split('.').pop().toLowerCase();
                        
                        if(ext == 'video' || ['mp4','avi','mov','wmv','flv','mkv'].includes(fileExt)) {
                            tool.videoView(href);
                        } else if(ext == 'audio' || ['mp3','wav','aac','ogg','wma'].includes(fileExt)) {
                            tool.audioView(href);
                        } else if(ext == 'image' || ['jpg','jpeg','png','gif','bmp','webp'].includes(fileExt)) {
                            tool.photoView(href);
                        } else if(ext == 'pdf' || fileExt == 'pdf') {
                            tool.pdfView(href);
                        } else if(ext == 'article') {
                            tool.articleView(id);
                        } else if((res.data.mimetype && res.data.mimetype.includes('wordprocessingml.document')) || 
                                 ['doc','docx'].includes(fileExt)) {
                            tool.officeView(id, 'word');
                        } else if(['xls','xlsx'].includes(fileExt)) {
                            tool.officeView(id, 'excel');
                        } else if(['ppt','pptx'].includes(fileExt)) {
                            tool.officeView(id, 'ppt');
                        } else if(['txt','csv','log'].includes(fileExt)) {
                            tool.textView(href);
                        } else {
                            layer.msg('不支持的文件类型: ' + fileExt);
                        }
                    } else {
                        layer.msg(res.msg);
                    }
                }
            });
        };
    
        var getDocTypeValue = function(cardType) {
            var typeMap = {
                '起诉状': 1,
                '委托代理材料': 2,
                '原被告身份证明': 3,
                '证据目录及证据材料': 4,
                '银行账户确认书': 5,
                '送达地址确认书': 6,
                '裁判文书/调解文书': 7,
                '其他': 8
            };
            return typeMap[cardType] || 0;
        };

        $('.doc-card').each(function(){
            var docTypeId = $(this).data('type-id');
            var table = $(this).find('table');
            
            // 初始化表格
            layui.table.render({
                elem: table[0],
                url: '/lawcase/api/get_casedoc_list',
                where: {
                    case_id: $('#case_id').val(),
                    doc_type: docTypeId
                },
                page: true,
                limit: 10,
                cols: [[
                    {field: 'title', title: '文档名称', templet: function(d){
                        return d.title || d.filename;
                    }},
                    {field: 'filename', title: '文件名', width: 200},
                    {field: 'size', title: '文件大小', width: 100},
                    {field: 'fileext', title: '文件类型', width: 100},
                    {field: 'create_time', title: '上传时间', width: 150, templet: function(d){
                        return d.create_time_text || d.create_time;
                    }},
                    {field: 'uploader', title: '上传人', width: 100},
                    {title: '操作', toolbar: '#docOperateBar', width: 150}
                ]],
                parseData: function(res){
                    // 将文件列表展开为单独行
                    var expandedData = [];
                    if(res.data && res.data.length > 0) {
                        res.data.forEach(function(doc) {
                            if(doc.files && doc.files.length > 0) {
                                doc.files.forEach(function(file) {
                                    expandedData.push({
                                        id: file.id,
                                        title: doc.title || file.filename, // 优先使用文档标题，没有则使用文件名
                                        filename: file.filename,
                                        size: file.size,
                                        fileext: file.fileext,
                                        create_time: file.file_create_time || '', // 直接输出原始值
                                        uploader: doc.uploader,
                                        doc_id: doc.id
                                    });
                                });
                            }
                        });
                    }
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": expandedData.length,
                        "data": expandedData
                    };
                }
            });
        });
    });
}

window.deleteDoc = function(id) {
    layui.layer.confirm('确定要删除该文档吗？', function(index) {

        $.ajax({
            url: '/lawcase/casedoc/delete',
            type: 'POST',
            data: {id: id},
            dataType: 'json',
            success: function(res) {
                layui.layer.close(index);
                if(res && res.code === 0) {

                    layui.layer.msg(res.msg || '删除成功');
                    // 重新加载当前文档类型的表格
                    var docCard = $('.doc-card[data-type-id="' + res.data.doc_type + '"]');
                    docCard.find('tbody').empty();
                    $.ajax({
                        url: '/lawcase/api/get_casedoc_list',
                        data: {case_id: case_id, doc_type: res.data.doc_type},
                        success: function(res){
                            if(res.code === 0) {
                                var html = '';
                                if(res.data.length === 0) {
                                    html = '<tr><td colspan="5" style="text-align:center;color:#999;">暂无数据</td></tr>';
                                } else {
                                    $.each(res.data, function(i, item){
                                        html += '<tr>';
                                        html += '<td>'+item.name+'</td>';
                                        html += '<td>'+item.size+'</td>';
                                        html += '<td>'+item.files[0].fileext+'</td>';
                                        html += '<td>'+new Date(item.create_time * 1000).toLocaleString()+'</td>';
                                        html += '<td>'+item.uploader+'</td>';
                                        html += '<td>';
                                        html += '<button class="layui-btn layui-btn-xs" onclick="previewDoc('+item.files[0].id+')">预览</button>';
                                        html += '<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteDoc('+item.id+')">删除</button>';
                                        html += '</td>';
                                        html += '</tr>';
                                    });
                                }
                                docCard.find('tbody').html(html);
                            }
                        }
                    });
                } else {

                    layui.layer.msg(res && res.msg ? res.msg : '删除失败');
                }
            },
            error: function(xhr, status, error) {

                layui.layer.close(index);
                layui.layer.msg('删除失败，请稍后重试');
            }
        });
    });
};

window.openUploadDoc = function(docTypeId) {
    var case_id = $('#case_id').val();
    var case_code = $('h3').text().match(/【(.*?)】/)[1];
    if(!case_id || case_id === '0') {
        layui.layer.msg('请先选择案件');
        return false;
    }
    
    layui.use(['tool'], function() {
        var tool = layui.tool;
        tool.side('/lawcase/casedoc/add?case_id=' + case_id + '&doc_type=' + docTypeId + '&case_code=' + encodeURIComponent(case_code), '上传文档');
    });
};
</script>